package tests.mytest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ReversingTreeWalker extends ElementTreeWalker {

	private Map<Node, List<Node>> levelInfo = new HashMap<Node, List<Node>>();
	
	
	@Override
	protected void processStart(Node node) {
		
		List<Node> children = new ArrayList<Node>();
		NodeList nextLevel = node.getChildNodes();
		for (int i=0; i<nextLevel.getLength(); i++) {
			children.add(nextLevel.item(i));
			
		}	
		levelInfo.put(node, children);
		
	}

	@Override
	protected void processEnd(Node node) {
		
		List<Node> children = levelInfo.get(node);
		Node prevChild = null;
		for (Node child : children) {
			if (prevChild != null) {
				node.insertBefore(child, prevChild);
			}
			prevChild = child;
		}

	}

}
